/**
 * Project Name:
 * File Name:LogonController.java
 * Package Name:com.clps.dev.sms.controller.sm
 * @date 2018-12-05 11:33:05 
 * Copyright (c) 2018, jackie.duan@clpsglobal.com All Rights Reserved.
 *
 */
package com.clps.dev.sms.controller.sm;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mindrot.jbcrypt.BCrypt;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.clps.dev.sms.common.CommonData;
import com.clps.dev.sms.common.result.ResponseResult;
import com.clps.dev.sms.common.result.ResultState;
import com.clps.dev.sms.common.result.ResultType;
import com.clps.dev.sms.entity.log.LoginLog;
import com.clps.dev.sms.entity.sm.Account;
import com.clps.dev.sms.entity.sm.Employee;
import com.clps.dev.sms.service.log.ILoginLogService;
import com.clps.dev.sms.service.sm.IAccountService;
import com.clps.dev.sms.service.sm.IEmployeeService;
import com.clps.dev.sms.util.createUrl.GenerateLinkUtils;
import com.clps.dev.sms.util.email.MailUtil;


/**
 * ClassName: LogonController 
 * @description
 * @date 2018-12-05 11:33:05 
 *
 * @author jackie.duan
 * @version V1.0
 * @since JDK 1.8
 */
@Controller
public class LogonController {
 
	@Resource
	private IAccountService accountService;
	@Resource
	private IEmployeeService employeeService;
	@Resource
	private ILoginLogService loginLogService;
	
	private Map<Integer, String> map = null;
	
	/**
	 * 
	 * showlogin
	 * @Description:跳转到登陆页面
	 * @param 
	 * @return String
	 */
	@GetMapping("/login")
	public String showlogin() {
		return "sm/login";
	}
	/**
	 * 
	 * showForget
	 * @Description:跳转到忘记密码页面
	 * @param
	 * @return String
	 */
	@GetMapping("/forget_pwd")
	public String showForget() {
		return "sm/forget_pwd";
	}
	/**
	 * 
	 * showresetPwd
	 * @Description:跳转到重置密码页面
	 * @param
	 * @return String
	 */
	@GetMapping("/reset")
	public String showResetPwd() {
		return "sm/reset_pwd";
	}
		/**
		 * 
		 * doLogin
		 * @Description:登陆
		 * @param accountName 用户名  accountPwd 用户密码
		 * @return String
		 */
		
		@PostMapping("/logon")
		public @ResponseBody ResponseResult<Account> doLogin(@RequestBody Account account,HttpServletRequest request, HttpSession session) {
			
          
			ResponseResult<Account> result= accountService.queryAccount(account.getAccountName());
			System.out.println(result.getMessage());
			Account account1 = (Account) result.getData();
			if(account1 == null) {
				//用户不存在，重定向到登陆页面
				result.setState(ResultState.NORETRUNDATA);
			}else{
				//用户存在
				ResponseResult<LoginLog> log = loginLogService.queryLoginLog(account1.getAccountName());
				LoginLog loginLog = (LoginLog) log.getData();
				//通过用户找到用户登陆日志
				if(loginLog == null) {
					//初次登陆
					if(account1.getAccountPassword().equals(account1.getAccountPassword())) {
						//用户密码正确
						//将用户id保存在session中
						session.setAttribute("accountId", account1.getAccountId());
						//用户初次登陆，跳转到重置密码页面
						result.setState(ResultState.FIRSTLOGIN);
						
					}else {
						//密码错误，重定向到登陆页面
						result.setState(ResultState.PASSWORDERROR);
						
					}
				}else {
					//非初次登陆,做加密之后的密码判断
					if(BCrypt.checkpw(account.getAccountPassword(), account1.getAccountPassword()) == true){
						//用户密码正确
						//将用户id保存在session中
						session.setAttribute("accountId", account1.getAccountId());
						loginLog = new LoginLog();
						loginLog.setAccountName(account1.getAccountName());
						loginLog.setIp(request.getLocalAddr());
						loginLogService.addLoginLog(loginLog);
						//添加用户登陆日志，跳转到登陆成功页面
						result.setState(ResultState.NOTFIRSTLOGIN);
						
					}else {
						//密码错误，重定向到登陆界面
						result.setState(ResultState.PASSWORDERROR);
						
					}
				}
			}
			return result;	
		}
	/**
	 * 
	 * forgetPwd
	 * @Description:忘记密码、发送邮件找回密码
	 * @param accountName 用户名  email 用户邮箱
	 * @return String
	 */
	@PostMapping("/forget")
	public @ResponseBody String forgetPwd(@RequestParam(value = "accountName")String accountName,@RequestParam(value = "email")String email,HttpServletRequest request, HttpSession session) {
		
		ResponseResult<Account> result= accountService.queryAccount(accountName);
		Account account = (Account) result.getData();
		if(account != null) {
			//用户名存在
			ResponseResult<Employee> rs = employeeService.queryEmployee(account.getAccountId());
			Employee employee = (Employee) rs.getData();
			if(employee.getEmpeMail().equals(email)) {
				//验证邮箱是否正确
				//将用户id保存在session中
				session.setAttribute("accountId", account.getAccountId());
				return "sm/reset_pwd";
			}else {
				//邮箱不正确，重定向忘记密码页面
				return "redirect:/forget_pwd";
			}
		}else {
			//用户名错误，重定向忘记密码页面
			return "redirect:/forget_pwd";
		}
	}

	@PostMapping("/quit")
	public String quit(HttpSession session) {
		session.removeAttribute("accoutId");
		return "redirect:/login";
	}

	/**
	 * 
	 * resetPwd
	 * @Description:重置密码
	 * @param changePassword 修改密码  checkPassword 确认密码
	 * @return String
	 */
	@PostMapping("/resetpwd")
	public String resetPwd(@RequestParam(value = "changePassword")String changePassword,@RequestParam(value = "checkPassword")String checkPassword,HttpServletRequest request,HttpSession session) throws Exception {
		
		if(!changePassword.contentEquals(" ") && !checkPassword.contentEquals(" ")) {
		if(changePassword.trim().length() >= 6 && checkPassword.trim().length() >= 6) {
			if(checkPassword.equals(changePassword)) {
				//两次密码输入一致
				//从session中获得用户id
				int accountId = Integer.parseInt(String.valueOf(session.getAttribute("accountId")));
				ResponseResult<Account> result = accountService.queryAccount(accountId);
				Account account = (Account) result.getData();
				
				map = new HashMap<Integer,String>();
				map.put(account.getAccountId(),changePassword);
				
				ResponseResult<Employee> rs = employeeService.queryEmployee(account.getAccountId());
				
				Timestamp outDate = new Timestamp(System.currentTimeMillis()+15*60*1000);
				
				long  validTime = outDate.getTime()/1000*1000;//忽略毫秒数
				
				//发邮件
				//账户id
				String id = String.valueOf(account.getAccountId());
				//有效时间
				String validtime = String.valueOf(validTime);
				
				String emailTitle = CommonData.EMAIL_TITLE;
				
				String path = request.getContextPath();
				String basePath = request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+path+"/";
				
				String resetPassHref = basePath+"confirm/"+id+"/"+validtime;
				
				String emailContent = "<a href=\'"+resetPassHref+"\'>点击我重新设置密码</a>" +
	                    "<br/>tips:本邮件超过30分钟,链接将会失效，需要重新申请'找回密码'";

				
				MailUtil mailUtil = new MailUtil();
				boolean flag = mailUtil.sendMail(CommonData.EMAIL_SENDER,  ((Employee) rs.getData()).getEmpeMail(), "", "", emailTitle,emailContent);
				if(flag == true) {
					//邮箱发送成功
					session.removeAttribute("accountId");
					return "sm/wait";
				}else {
					//邮箱发送失败
					return "sm/reset_pwd";
				}
			}else {
				return "sm/reset_pwd";
			}
		}else {
			return "sm/reset_pwd";
		}
		}else {
			return "sm/reset_pwd";
		}
	}

	@GetMapping("/confirm/{accountId}/{validtime}")
	public String checkRestLink(@PathVariable(name="accountId",required=true)String accountId,@PathVariable(name="validtime",required=true)String validtime,HttpServletRequest request,Model model) throws NumberFormatException, Exception {
		String msg = "";
		//比较链接时间是否有效
		Timestamp nowDate = new Timestamp(System.currentTimeMillis());
		if(Long.parseLong(validtime) <= nowDate.getTime()) {//表示已经过期
			
			msg = CommonData.VALID_LINK;
			model.addAttribute("msg", msg);
			String key = GenerateLinkUtils.generateLoginLink();
			model.addAttribute("key", key);
			return "sm/wait";
		}
		ResponseResult<Account> re = accountService.queryAccount(Integer.parseInt(accountId));
		Account account = (Account) re.getData();
		//修改密码
		account.setAccountPassword(BCrypt.hashpw(map.get(account.getAccountId()), BCrypt.gensalt()));
		map.remove(account.getAccountId());
		ResponseResult<Account> result = accountService.editAccount(account);
		if (ResultType.UPDATE_SUCCESS.equals(result.getMessage())) {
			//重置密码成功
			ResponseResult<LoginLog> logResult = loginLogService.queryLoginLog(account.getAccountName());//通过账户id找到账户日志判断是否初次登陆
			LoginLog loginLog = (LoginLog) logResult.getData();
			loginLog = new LoginLog();
			loginLog.setAccountName(account.getAccountName());
			loginLog.setIp(request.getLocalAddr());
			loginLogService.addLoginLog(loginLog);
			msg = CommonData.CONFIRM_SUCCESS;
			model.addAttribute("msg", msg);
			String key = GenerateLinkUtils.generateLoginLink();
			model.addAttribute("key", key);
			return "sm/wait";
			
		} else {
			msg = CommonData.CONFIRM_FAILURE;
			model.addAttribute("msg", msg);
			String key = GenerateLinkUtils.generateLoginLink();
			model.addAttribute("key", key);
			return "sm/wait";
		}
	}
}
